<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>高级电工考试题库</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f5f5f5;
        }
        .container {
            max-width: 600px;
            margin: 0 auto;
            background-color: #fff;
            min-height: 100vh;
        }
        .header {
            display: flex;
            position: relative;
            height: 50px;
        }
        .library-selector {
            width: 100px;
            height: 35px;
            margin: 7.5px 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            background: white;
            font-size: 14px;
            cursor: pointer;
        }
        .question-file-selector {
            width: 150px;
            height: 35px;
            margin: 7.5px 5px;
            border: 1px solid #ddd;
            border-radius: 5px;
            background: white;
            font-size: 14px;
            cursor: pointer;
        }
        .question-selector {
            width: 120px;
            height: 35px;
            margin: 7.5px 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            background: white;
            font-size: 14px;
            cursor: pointer;
        }
        .question-input {
            width: 80px;
            height: 35px;
            margin: 7.5px 5px;
            border: 1px solid #ddd;
            border-radius: 5px;
            padding: 0 8px;
            font-size: 14px;
            text-align: center;
        }
        .question-input:focus {
            outline: none;
            border-color: #1a8cff;
        }
        .nav-container {
            flex: 1;
            border-bottom: 1px solid #e0e0e0;
        }
        .nav-tabs {
            display: flex;
            height: 100%;
            overflow: hidden;
        }
        .nav-tab {
            flex: 1;
            display: flex;
            justify-content: center;
            align-items: center;
            border: none;
            background: #f0f0f0;
            cursor: pointer;
        }
        .nav-tab.active {
            background: #1a8cff;
            color: white;
        }
        .settings-button {
            width: 50px;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 20px;
            background: none;
            border: none;
            cursor: pointer;
        }
        .question-container {
            padding: 15px;
            position: relative;
        }
        .question-type {
            display: inline-block;
            color: white;
            background-color: #1a73e8;
            padding: 3px 10px;
            border-radius: 15px;
            font-size: 14px;
            margin-bottom: 10px;
        }
        .question-type.multiple-choice {
            background-color: #ff5722;
        }
        .multiple-choice-hint {
            background-color: #fff3e0;
            border-left: 4px solid #ff5722;
            padding: 10px;
            margin: 10px 0;
            font-size: 14px;
            color: #e65100;
        }
        .question-content {
            font-size: 18px;
            line-height: 1.5;
            margin-bottom: 20px;
        }
        .options-container {
            margin-bottom: 20px;
        }
        .option {
            display: flex;
            margin-bottom: 15px;
            border: 1px solid #e0e0e0;
            border-radius: 50px;
            padding: 10px 15px;
            cursor: pointer;
        }
        .option.selected {
            border-color: #1a8cff;
            background-color: #e6f3ff;
        }
        .option-key {
            width: 25px;
            height: 25px;
            border-radius: 50%;
            background-color: #f0f0f0;
            display: flex;
            justify-content: center;
            align-items: center;
            margin-right: 15px;
        }
        .option.selected .option-key {
            background-color: #1a8cff;
            color: white;
        }
        .option-value {
            flex: 1;
            display: flex;
            align-items: center;
        }
        .footer {
            display: flex;
            justify-content: space-between;
            padding: 15px;
            border-top: 1px solid #e0e0e0;
        }
        .navigation-buttons {
            display: flex;
        }
        .nav-button {
            padding: 10px 15px;
            margin-left: 10px;
            background: #f0f0f0;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }
        .submit-button {
            padding: 10px 20px;
            background-color: #1a8cff;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }
        .result-container {
            padding: 15px;
            margin-top: 10px;
            border-top: 1px solid #e0e0e0;
            display: none;
        }
        .result-correct {
            color: #4caf50;
            font-weight: bold;
        }
        .result-incorrect {
            color: #f44336;
            font-weight: bold;
        }
        .explanation {
            margin-top: 10px;
            padding: 10px;
            background-color: #f5f5f5;
            border-radius: 5px;
        }
        .progress {
            text-align: center;
            font-size: 14px;
            color: #666;
            padding: 10px 0;
        }
        .hidden {
            display: none;
        }
        .delete-button {
            position: absolute;
            top: 10px;
            right: 10px;
            background-color: #f44336;
            color: white;
            border: none;
            border-radius: 3px;
            padding: 5px 10px;
            font-size: 12px;
            cursor: pointer;
            display: none;
        }
        .delete-button:hover {
            background-color: #d32f2f;
        }
        .delete-all-button {
            position: absolute;
            top: 10px;
            right: 80px;
            background-color: #d32f2f;
            color: white;
            border: none;
            border-radius: 3px;
            padding: 5px 8px;
            font-size: 12px;
            cursor: pointer;
            display: none;
        }
        .delete-all-button:hover {
            background-color: #b71c1c;
        }
        .question-container.wrong-mode .delete-button {
            display: block;
        }
        .question-container.wrong-mode .delete-all-button {
            display: block;
        }
    </style>
</head>
<body>
    <div class="container">
                <div class="header">
            <select class="library-selector" id="librarySelector">
                <option value="main">主题库</option>
                <option value="wrong">错题库</option>
            </select>
            <select class="question-file-selector" id="questionFileSelector">
                <option value="">加载中...</option>
            </select>
            <select class="question-selector" id="questionSelector">
                <option value="">选择题目范围</option>
            </select>
            <input type="number" class="question-input" id="questionInput" placeholder="题号" min="1">
            <div class="nav-container">
                <div class="nav-tabs">
                    <button class="nav-tab active" data-mode="answer">答题</button>
                    <button class="nav-tab" data-mode="wrong">错题</button>
                </div>
            </div>
            <button class="settings-button">⚙️</button>
        </div>
        
        <div class="question-container">
            <button class="delete-all-button" id="deleteAllButton">全部删除</button>
            <button class="delete-button" id="deleteButton">删除</button>
            <div class="question-type"></div>
            <div class="question-content"></div>
            <div class="multiple-choice-hint" style="display: none;"></div>
            <div class="options-container"></div>
        </div>
        
        <div class="result-container">
            <div class="result-message"></div>
            <div class="explanation"></div>
        </div>
        
        <div class="progress"></div>
        
        <div class="footer">
            <button class="submit-button">提交</button>
            <div class="navigation-buttons">
                <button class="nav-button prev-button">上一题</button>
                <button class="nav-button next-button">下一题</button>
            </div>
        </div>
    </div>

    <script>
        let questions = [];
        let wrongQuestions = [];
        let questionFiles = [];
        let currentQuestionFile = '';
        let currentLibrary = 'main';
        let currentQuestionIndex = 0;
        let selectedOption = null;
        let selectedOptions = [];

        // 页面加载完成后初始化
        window.addEventListener('DOMContentLoaded', async () => {
            try {
                // 加载题库文件列表
                await loadQuestionFiles();
                
                // 加载主题库
                const response = await fetch('/api/questions');
                questions = await response.json();
                
                // 加载错题库
                const wrongResponse = await fetch('/api/wrong-questions');
                wrongQuestions = await wrongResponse.json();
                
                // 获取当前题库文件信息
                const currentFileResponse = await fetch('/api/current-question-file');
                const currentFileInfo = await currentFileResponse.json();
                currentQuestionFile = currentFileInfo.filename;
                
                // 设置题库文件选择器的当前值
                document.getElementById('questionFileSelector').value = currentQuestionFile;
                
                // 初始状态下显示题库文件选择器（因为默认是主题库模式）
                document.getElementById('questionFileSelector').style.display = 'block';
                
                initializeQuestionSelector();
                updateProgress();
                displayQuestion(currentQuestionIndex);
            } catch (error) {
                console.error('初始化失败:', error);
            }
        });

        // 加载题库文件列表
        async function loadQuestionFiles() {
            try {
                const response = await fetch('/api/question-files');
                questionFiles = await response.json();
                
                const selector = document.getElementById('questionFileSelector');
                selector.innerHTML = '';
                
                questionFiles.forEach(file => {
                    const option = document.createElement('option');
                    option.value = file.filename;
                    option.textContent = file.display_name;
                    selector.appendChild(option);
                });
                
                // 设置默认选中项
                if (questionFiles.length > 0) {
                    selector.value = questionFiles[0].filename;
                }
            } catch (error) {
                console.error('加载题库文件列表失败:', error);
            }
        }

        // 切换题库文件
        async function switchQuestionFile(filename) {
            if (!filename) return Promise.resolve();
            
            try {
                const response = await fetch('/api/switch-question-file', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ filename: filename }),
                });
                
                if (response.ok) {
                    // 重新加载题目
                    const questionsResponse = await fetch('/api/questions');
                    questions = await questionsResponse.json();
                    
                    // 重置状态
                    currentQuestionIndex = 0;
                    currentQuestionFile = filename;
                    
                    // 重新初始化
                    initializeQuestionSelector();
                    displayQuestion(currentQuestionIndex);
                    
                    console.log(`已切换到题库: ${filename}`);
                    return Promise.resolve();
                } else {
                    alert('切换题库失败，请重试');
                    return Promise.reject();
                }
            } catch (error) {
                console.error('切换题库失败:', error);
                alert('切换题库失败，请检查网络连接');
                return Promise.reject(error);
            }
        }

        // 初始化题目选择器
        function initializeQuestionSelector() {
            const selector = document.getElementById('questionSelector');
            selector.innerHTML = '<option value="">选择题目范围</option>';
            
            const currentQuestions = getCurrentQuestions();
            const totalQuestions = currentQuestions.length;
            const groupSize = 100;
            
            for (let i = 0; i < totalQuestions; i += groupSize) {
                const start = i + 1;
                const end = Math.min(i + groupSize, totalQuestions);
                const option = document.createElement('option');
                option.value = i;
                option.textContent = `第${start}-${end}题`;
                selector.appendChild(option);
            }
        }

        // 获取当前题库
        function getCurrentQuestions() {
            if (currentLibrary === 'wrong') {
                // 只返回当前题库文件的错题
                return wrongQuestions.filter(q => q.source_file === currentQuestionFile);
            }
            return questions;
        }

        // 删除错题
        async function deleteWrongQuestion() {
            if (currentLibrary !== 'wrong') {
                return;
            }
            
            const currentWrongQuestions = getCurrentQuestions();
            if (currentWrongQuestions.length === 0) {
                return;
            }
            
            const currentQuestion = currentWrongQuestions[currentQuestionIndex];
            
            if (confirm('确定要删除这道错题吗？')) {
                try {
                    const response = await fetch(`/api/wrong-questions/${currentQuestion.id}`, {
                        method: 'DELETE',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({
                            source_file: currentQuestion.source_file || currentQuestionFile
                        })
                    });
                    
                    if (response.ok) {
                        // 重新加载错题库
                        const wrongResponse = await fetch('/api/wrong-questions');
                        wrongQuestions = await wrongResponse.json();
                        
                        // 更新当前显示的错题列表
                        const updatedWrongQuestions = getCurrentQuestions();
                        
                        // 调整当前题目索引
                        if (currentQuestionIndex >= updatedWrongQuestions.length) {
                            currentQuestionIndex = Math.max(0, updatedWrongQuestions.length - 1);
                        }
                        
                        // 重新初始化
                        initializeQuestionSelector();
                        if (updatedWrongQuestions.length > 0) {
                            displayQuestion(currentQuestionIndex);
                        } else {
                            // 如果当前题库错题为空，切换到主题库
                            currentLibrary = 'main';
                            document.getElementById('librarySelector').value = 'main';
                            document.querySelector('[data-mode="answer"]').classList.add('active');
                            document.querySelector('[data-mode="wrong"]').classList.remove('active');
                            document.getElementById('questionFileSelector').style.display = 'block';
                            initializeQuestionSelector();
                            displayQuestion(0);
                        }
                    }
                } catch (error) {
                    console.error('删除错题失败:', error);
                    alert('删除失败，请重试');
                }
            }
        }

        // 全部删除错题
        async function deleteAllWrongQuestions() {
            if (currentLibrary !== 'wrong') {
                return;
            }
            
            const currentWrongQuestions = getCurrentQuestions();
            const totalWrongQuestions = wrongQuestions.length;
            
            if (totalWrongQuestions === 0) {
                alert('错题库为空！');
                return;
            }
            
            // 提供删除选项
            let deleteType = '';
            if (currentWrongQuestions.length > 0 && currentWrongQuestions.length < totalWrongQuestions) {
                // 当前题库有错题，且总错题数更多，提供选择
                const choice = confirm(`选择删除范围：\n\n确定 - 删除当前题库的 ${currentWrongQuestions.length} 道错题\n取消 - 删除全部 ${totalWrongQuestions} 道错题`);
                deleteType = choice ? 'current' : 'all';
            } else if (currentWrongQuestions.length === totalWrongQuestions) {
                // 所有错题都来自当前题库
                if (confirm(`确定要删除全部 ${totalWrongQuestions} 道错题吗？此操作不可撤销！`)) {
                    deleteType = 'all';
                }
            } else {
                // 当前题库没有错题
                if (confirm(`当前题库没有错题。\n确定要删除全部 ${totalWrongQuestions} 道错题吗？此操作不可撤销！`)) {
                    deleteType = 'all';
                }
            }
            
            if (deleteType) {
                try {
                    const endpoint = deleteType === 'current' ? '/api/wrong-questions/current' : '/api/wrong-questions/all';
                    const response = await fetch(endpoint, {
                        method: 'DELETE',
                    });
                    
                    if (response.ok) {
                        // 重新加载错题库
                        const wrongResponse = await fetch('/api/wrong-questions');
                        wrongQuestions = await wrongResponse.json();
                        
                        const updatedWrongQuestions = getCurrentQuestions();
                        
                        if (updatedWrongQuestions.length === 0) {
                            // 如果当前题库错题为空，切换到主题库
                            currentLibrary = 'main';
                            document.getElementById('librarySelector').value = 'main';
                            document.querySelector('[data-mode="answer"]').classList.add('active');
                            document.querySelector('[data-mode="wrong"]').classList.remove('active');
                            document.getElementById('questionFileSelector').style.display = 'block';
                        }
                        
                        // 重新初始化
                        currentQuestionIndex = 0;
                        initializeQuestionSelector();
                        if (updatedWrongQuestions.length > 0) {
                            displayQuestion(0);
                        } else {
                            displayQuestion(0); // 切换到主题库第一题
                        }
                        
                        const message = deleteType === 'current' ? '当前题库错题已清空！' : '错题库已清空！';
                        alert(message);
                    }
                } catch (error) {
                    console.error('清空错题库失败:', error);
                    alert('清空失败，请重试');
                }
            }
        }

        // 显示当前题目
        function displayQuestion(index) {
            const currentQuestions = getCurrentQuestions();
            if (index < 0 || index >= currentQuestions.length) {
                return;
            }

            const question = currentQuestions[index];
            currentQuestionIndex = index;
            selectedOption = null;
            selectedOptions = [];
            
            const questionTypeElement = document.querySelector('.question-type');
            questionTypeElement.textContent = question.type;
            questionTypeElement.className = 'question-type';
            if (question.type === '多选题') {
                questionTypeElement.classList.add('multiple-choice');
            }
            
            document.querySelector('.question-content').textContent = question.content;
            
            const optionsContainer = document.querySelector('.options-container');
            optionsContainer.innerHTML = '';
            
            // 为多选题显示提示
            const hintElement = document.querySelector('.multiple-choice-hint');
            if (question.type === '多选题') {
                hintElement.textContent = '⚠️ 多选题：请选择所有正确答案，可以点击多个选项';
                hintElement.style.display = 'block';
            } else {
                hintElement.style.display = 'none';
            }
            
            question.options.forEach(option => {
                const optionElement = document.createElement('div');
                optionElement.className = 'option';
                
                optionElement.innerHTML = `
                    <div class="option-key">${option.key}</div>
                    <div class="option-value">${option.value}</div>
                `;
                
                optionElement.addEventListener('click', () => {
                    if (question.type === '多选题') {
                        // 多选题逻辑
                        if (optionElement.classList.contains('selected')) {
                            optionElement.classList.remove('selected');
                            selectedOptions = selectedOptions.filter(opt => opt !== option.key);
                        } else {
                            optionElement.classList.add('selected');
                            selectedOptions.push(option.key);
                        }
                    } else {
                        // 单选题逻辑
                        document.querySelectorAll('.option').forEach(el => el.classList.remove('selected'));
                        optionElement.classList.add('selected');
                        selectedOption = option.key;
                    }
                });
                
                optionsContainer.appendChild(optionElement);
            });
            
            // 隐藏结果区域
            document.querySelector('.result-container').style.display = 'none';
            
            // 更新进度
            updateProgress();
            
            // 在错题库模式下显示删除按钮，并更新按钮文本
            const container = document.querySelector('.question-container');
            if (currentLibrary === 'wrong' && getCurrentQuestions().length > 0) {
                container.classList.add('wrong-mode');
                
                // 更新删除按钮文本
                const deleteAllButton = document.getElementById('deleteAllButton');
                const currentWrongQuestions = getCurrentQuestions();
                const totalWrongQuestions = wrongQuestions.length;
                
                if (currentWrongQuestions.length < totalWrongQuestions) {
                    deleteAllButton.textContent = `删除当前题库 (${currentWrongQuestions.length}题)`;
                } else {
                    deleteAllButton.textContent = `全部删除 (${totalWrongQuestions}题)`;
                }
            } else {
                container.classList.remove('wrong-mode');
            }
        }

        // 提交答案
        async function submitAnswer() {
            const currentQuestions = getCurrentQuestions();
            const question = currentQuestions[currentQuestionIndex];
            let userAnswer = '';
            
            if (question.type === '多选题') {
                if (selectedOptions.length === 0) {
                    alert('请选择至少一个选项');
                    return;
                }
                userAnswer = selectedOptions.sort().join('');
            } else {
                if (!selectedOption) {
                    alert('请选择一个选项');
                    return;
                }
                userAnswer = selectedOption;
            }

            try {
                const response = await fetch('/api/check', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        questionId: question.id,
                        answer: userAnswer
                    }),
                });
                
                const result = await response.json();
                
                // 如果答错了且在主题库中，添加到错题库
                if (!result.correct && currentLibrary === 'main') {
                    await addToWrongQuestions(currentQuestions[currentQuestionIndex]);
                }
                
                // 显示结果
                const resultContainer = document.querySelector('.result-container');
                const resultMessage = document.querySelector('.result-message');
                const explanation = document.querySelector('.explanation');
                
                resultContainer.style.display = 'block';
                
                if (result.correct) {
                    resultMessage.innerHTML = '<span class="result-correct">正确！</span>';
                } else {
                    resultMessage.innerHTML = `<span class="result-incorrect">错误！</span> 正确答案是: ${result.correctAnswer}`;
                }
                
                explanation.textContent = result.explanation || '暂无解析';
                
            } catch (error) {
                console.error('提交答案失败:', error);
            }
        }

        // 添加题目到错题库
        async function addToWrongQuestions(question) {
            try {
                const response = await fetch('/api/wrong-questions', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(question),
                });
                
                if (response.ok) {
                    // 重新加载错题库
                    const wrongResponse = await fetch('/api/wrong-questions');
                    wrongQuestions = await wrongResponse.json();
                }
            } catch (error) {
                console.error('添加错题失败:', error);
            }
        }

        // 更新进度显示
        function updateProgress() {
            const currentQuestions = getCurrentQuestions();
            document.querySelector('.progress').textContent = `${currentQuestionIndex + 1} / ${currentQuestions.length}`;
            
            // 更新下拉框选择状态
            const selector = document.getElementById('questionSelector');
            const groupSize = 100;
            const groupIndex = Math.floor(currentQuestionIndex / groupSize) * groupSize;
            selector.value = groupIndex;
            
            // 更新输入框的最大值和当前值
            const input = document.getElementById('questionInput');
            input.max = currentQuestions.length;
            input.value = currentQuestionIndex + 1;
        }

        // 绑定事件
        document.querySelector('.submit-button').addEventListener('click', submitAnswer);
        
        document.querySelector('.prev-button').addEventListener('click', () => {
            if (currentQuestionIndex > 0) {
                displayQuestion(currentQuestionIndex - 1);
            }
        });
        
        document.querySelector('.next-button').addEventListener('click', () => {
            const currentQuestions = getCurrentQuestions();
            
            // 检查是否已经提交过当前题目
            const hasSubmitted = document.querySelector('.result-container').style.display !== 'none';
            
            if (hasSubmitted) {
                // 如果已经提交，直接进入下一题
                if (currentQuestionIndex < currentQuestions.length - 1) {
                    displayQuestion(currentQuestionIndex + 1);
                }
            } else {
                // 如果没有提交，先提交当前答案，不自动跳转
                submitAnswer();
            }
        });
        
        // 导航切换
        document.querySelectorAll('.nav-tab').forEach(tab => {
            tab.addEventListener('click', () => {
                document.querySelectorAll('.nav-tab').forEach(t => t.classList.remove('active'));
                tab.classList.add('active');
                
                const mode = tab.getAttribute('data-mode');
                if (mode === 'wrong') {
                    currentLibrary = 'wrong';
                    document.getElementById('librarySelector').value = 'wrong';
                    // 隐藏题库文件选择器
                    document.getElementById('questionFileSelector').style.display = 'none';
                } else {
                    currentLibrary = 'main';
                    document.getElementById('librarySelector').value = 'main';
                    // 显示题库文件选择器
                    document.getElementById('questionFileSelector').style.display = 'block';
                }
                
                currentQuestionIndex = 0;
                initializeQuestionSelector();
                
                // 检查当前模式下是否有题目
                const currentQuestions = getCurrentQuestions();
                if (currentQuestions.length > 0) {
                    displayQuestion(currentQuestionIndex);
                } else if (mode === 'wrong') {
                    // 如果错题库为空，显示提示并切换回主题库
                    alert('当前题库没有错题！');
                    // 切换回答题模式
                    currentLibrary = 'main';
                    document.getElementById('librarySelector').value = 'main';
                    document.querySelector('[data-mode="answer"]').classList.add('active');
                    document.querySelector('[data-mode="wrong"]').classList.remove('active');
                    document.getElementById('questionFileSelector').style.display = 'block';
                    initializeQuestionSelector();
                    displayQuestion(0);
                } else {
                    displayQuestion(currentQuestionIndex);
                }
            });
        });
        
        // 题库选择器
        document.getElementById('librarySelector').addEventListener('change', (e) => {
            currentLibrary = e.target.value;
            currentQuestionIndex = 0;
            
            // 更新标签页状态
            document.querySelectorAll('.nav-tab').forEach(t => t.classList.remove('active'));
            if (currentLibrary === 'wrong') {
                document.querySelector('[data-mode="wrong"]').classList.add('active');
                // 隐藏题库文件选择器
                document.getElementById('questionFileSelector').style.display = 'none';
            } else {
                document.querySelector('[data-mode="answer"]').classList.add('active');
                // 显示题库文件选择器
                document.getElementById('questionFileSelector').style.display = 'block';
            }
            
            initializeQuestionSelector();
            displayQuestion(currentQuestionIndex);
        });
        
        // 题库文件选择器
        document.getElementById('questionFileSelector').addEventListener('change', (e) => {
            const selectedFile = e.target.value;
            if (selectedFile && selectedFile !== currentQuestionFile) {
                switchQuestionFile(selectedFile).then(() => {
                    // 切换题库后，如果当前在错题库模式，检查是否有错题
                    if (currentLibrary === 'wrong') {
                        const currentWrongQuestions = getCurrentQuestions();
                        if (currentWrongQuestions.length === 0) {
                            alert('当前题库没有错题！切换到答题模式。');
                            // 切换到答题模式
                            currentLibrary = 'main';
                            document.getElementById('librarySelector').value = 'main';
                            document.querySelector('[data-mode="answer"]').classList.add('active');
                            document.querySelector('[data-mode="wrong"]').classList.remove('active');
                            initializeQuestionSelector();
                            displayQuestion(0);
                        } else {
                            // 有错题，重新显示
                            initializeQuestionSelector();
                            displayQuestion(0);
                        }
                    }
                });
            }
        });
        
        // 题目选择器事件
        document.getElementById('questionSelector').addEventListener('change', (e) => {
            const selectedIndex = parseInt(e.target.value);
            const currentQuestions = getCurrentQuestions();
            if (!isNaN(selectedIndex) && selectedIndex >= 0 && selectedIndex < currentQuestions.length) {
                displayQuestion(selectedIndex);
            }
        });
        
        // 题目输入框事件
        document.getElementById('questionInput').addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                const questionNumber = parseInt(e.target.value);
                const currentQuestions = getCurrentQuestions();
                if (questionNumber >= 1 && questionNumber <= currentQuestions.length) {
                    displayQuestion(questionNumber - 1); // 转换为0基索引
                } else {
                    alert(`请输入1到${currentQuestions.length}之间的题号`);
                    e.target.value = currentQuestionIndex + 1; // 恢复当前题号
                }
            }
        });
        
        // 输入框失焦验证
        document.getElementById('questionInput').addEventListener('blur', (e) => {
            const questionNumber = parseInt(e.target.value);
            const currentQuestions = getCurrentQuestions();
            if (isNaN(questionNumber) || questionNumber < 1 || questionNumber > currentQuestions.length) {
                e.target.value = currentQuestionIndex + 1; // 恢复当前题号
            }
        });
        
        // 右键功能：提交答案或下一题
        document.addEventListener('contextmenu', (e) => {
            e.preventDefault(); // 阻止右键菜单显示
            
            const currentQuestions = getCurrentQuestions();
            
            // 检查是否已经提交过当前题目
            const currentQuestionId = currentQuestions[currentQuestionIndex]?.id;
            const hasSubmitted = document.querySelector('.result-container').style.display !== 'none';
            
            if (hasSubmitted) {
                // 如果已经提交，进入下一题
                if (currentQuestionIndex < currentQuestions.length - 1) {
                    displayQuestion(currentQuestionIndex + 1);
                }
            } else {
                // 如果没有提交，提交当前答案
                submitAnswer();
            }
        });
        
        // 删除按钮事件
        document.getElementById('deleteButton').addEventListener('click', deleteWrongQuestion);
        
        // 全部删除按钮事件
        document.getElementById('deleteAllButton').addEventListener('click', deleteAllWrongQuestions);
    </script>
</body>
</html> 